﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;


namespace IdCardReader
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private int ConnectedCardReaderPort = 0;

        private void FindReader()
        {
            int uiCurrBaud = 0;		//串口号
            int nRet, nRet2;		//用于接收返回值
            int m_iPort = 0;
            
            nRet = ReadCardAPI.Syn_FindReader();

            if (nRet == 0)
            {
                this.Invoke(new Action(() =>
                {
                    MessageBox.Show(this, $"没有找到读卡器", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }));
                
            }
            else
            {
                m_iPort = nRet;
                if (nRet > 1000)
                {
                    this.Invoke(new Action(() =>
                    {
                        MessageBox.Show($"读卡器连接连接在 USB{nRet}", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }));
                    
                }
                else
                {
                    Thread.Sleep(200);
                    nRet2 = ReadCardAPI.Syn_GetCOMBaud(nRet, ref uiCurrBaud);


                    this.Invoke(new Action(() =>
                    {
                        MessageBox.Show($"读卡器连接在串口 {nRet} 当前SAM波特率为 {uiCurrBaud }", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }));
                    
                }
            }

            this.ConnectedCardReaderPort = m_iPort;
        }


        /// <summary>
        /// 读卡(含指纹)
        /// </summary>
        private void ReadCardWithFinger()
        {
            int nRet;
            int m_iPort = ConnectedCardReaderPort;
            byte[] pucIIN = new byte[4];
            byte[] pucSN = new byte[8];
            IDCardData idcardData = new IDCardData();
            byte[] ctmp = new byte[255];
            byte[] szPathP = new byte[260];
            ReadCardAPI.Syn_SetPhotoPath(1, ref ctmp);
            
            ReadCardAPI.SetupDataFormate(1);
            nRet = ReadCardAPI.Syn_OpenPort(m_iPort);

            //Syn_USBSetTransportType(m_iPort,((CButton*)GetDlgItem(IDC_CHECK2))->GetCheck());

            if(nRet != 0)
            {

                this.Invoke(new Action(() =>
                {
                    MessageBox.Show("打开端口错误", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }));
                
                return;
            }

            nRet = ReadCardAPI.Syn_StartFindIDCard(m_iPort, ref pucIIN, 0);
            Thread.Sleep(10);
            nRet = ReadCardAPI.Syn_SelectIDCard(m_iPort, ref pucSN, 0);
            Thread.Sleep(10);
            nRet = ReadCardAPI.Syn_ReadFPMsg(m_iPort, 0, ref idcardData, szPathP);
            string szPath = Encoding.Default.GetString(szPathP);


            if(nRet != 0 && nRet != 1)
            {
                this.Invoke(new Action(() =>
                {
                    MessageBox.Show("读取身份证信息错误", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }));
                
                return;
            }

            //0读取身份证信息成功，1读取身份证信息成功，解码照片不成功，其他.读取身份证信息失败
            if (nRet == 1)
            {
                this.Invoke(new Action(() =>
                {
                    this.lblFingerFileName.Text = szPath;
                }));
                
            }
            else
            {
                this.Invoke(new Action(() =>
                {
                    MessageBox.Show("没有指纹信息", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }));
                
            }

            this.Invoke(new Action(() =>
            {
                this.lblName.Text = idcardData.Name;
                this.lblGender.Text = idcardData.Sex;
                this.lblNation.Text = idcardData.Nation;
                this.lblBirthday.Text = idcardData.Born;
                this.lblAddress.Text = idcardData.Address;
                this.lblCardFrom.Text = idcardData.GrantDept;
                this.lblEffectiveDateRange.Text = $"{idcardData.UserLifeBegin} ~ {idcardData.UserLifeEnd}";
                this.lblIdCardNo.Text = idcardData.IDCardNo;
                this.lblAvatarFileName.Text = idcardData.PhotoFileName;
                //这样做可以及时释放文件占用，否则第二次刷卡会报错
                using (Image tmp = Image.FromFile(idcardData.PhotoFileName))
                {
                    Bitmap img = new Bitmap(tmp);
                    this.pboxAvatar.Image = img;
                }
            }));

            
            if (m_iPort > 0)
            {
                ReadCardAPI.Syn_ClosePort(m_iPort);
            }

        }

        /// <summary>
        /// 窗体加载事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_Load(object sender, EventArgs e)
        {
            // 异步寻读卡器
            Task.Run(() =>
            {
                FindReader();
            });
            
        }

        /// <summary>
        /// 读卡按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnReadCard_Click(object sender, EventArgs e)
        {
            // 带指纹异步读卡
            Task.Run(() =>
            {
                this.ReadCardWithFinger();
            });
        }

        /// <summary>
        /// 测试读卡器连接按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnTestConnection_Click(object sender, EventArgs e)
        {
            // 异步寻读卡器
            Task.Run(() =>
            {
                this.FindReader();
            });
        }
    }
}
